// Copyright (C) 2012 Yoshiki Shibata. All rights reserved.

package main

import "net"
import "encoding/json"

type ChatSender struct {
	userName string
}

func NewChatSender(userName string) *ChatSender {
	sender := new(ChatSender)
	sender.userName = userName
	return sender
}

func (sender *ChatSender) sendMessage(
		recipient string, message string, cookie int, resultChan chan int) {
	recipientAddress := recipient + ":55555"

	conn, e := net.Dial("tcp", recipientAddress)
	if e != nil {
		resultChan <- -cookie
		return
	}
	msg := Message{1, sender.userName, recipient, message}
	b, _ := json.Marshal(msg)
	_, we := conn.Write(b)
	if we != nil {
		conn.Close()
		resultChan <- -cookie
		return
	}
	conn.Close()
	resultChan <- cookie
}

// Sends a message to the specified receipients. As a return value,
// an array of bool indicating success or failure for each receipient.
func (sender *ChatSender) Send(recipients [] string, message string) []bool {
	results := make([]bool, len(recipients))
	resultChan := make(chan int)

	for i := 0; i < len(recipients); i++ {
		go sender.sendMessage(recipients[i], message, i+1, resultChan)
	}
	
	for i := 0; i < len(recipients); i++ {
		cookie := <- resultChan
		if cookie > 0 {
			results[cookie - 1] = true
		} else {
			results[-cookie -1] = false
		}
	}
	return results
}
